<?php
include __DIR__.'/vendor/autoload.php';
include __DIR__.'/aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config.php';
//要解析的域名
static $domain = '';
use GuzzleHttp\Client;
use PHPHtmlParser\Dom;
use Domain\Request\V20180129\QueryDomainListRequest;
use Alidns\Request\V20150109\DescribeDomainRecordsRequest;
use Alidns\Request\V20150109\AddDomainRecordRequest;
use Alidns\Request\V20150109\UpdateDomainRecordRequest;
//阿里云AccessKey
$AccessKey = "";
//阿里云的 AccessKeySecret
$AccessKeySecret = "";
$Client = new Client();
//$Client->set;
try {
    $res = $Client->request('GET', 'https://ip.cn',[
        'verify'=>false
    ]);
    $str = $res->getBody();
    $dom = new Dom();
    $code = $dom->load($str)->find('code')[0];
    $ip =  $code->text;
    $iClientProfile = DefaultProfile::getProfile("cn-hangzhou", $AccessKey, $AccessKeySecret);
    $client = new DefaultAcsClient($iClientProfile);
//    $request = new QueryDomainListRequest();
//    $request->setPageNum(1);
//    $request->setPageSize(99);
//    $request->setDomainName('liuziqing.cn');
    $request = new DescribeDomainRecordsRequest();
    $request->setDomainName($domain);
    $result = $client->getAcsResponse($request);
    $record = $result->DomainRecords->Record;
    /**
     * 如果没有解析，添加解析
     */
    if (!count($record)){
        $request = new AddDomainRecordRequest();
        $request->setDomainName($domain);
        $request->setType('A');
        $request->setRR('*');
        $request->setValue($ip);
        $result = $client->getAcsResponse($request);
        writeLog(['action'=>'add_record','ip'=>$ip]);
    }else{
        /**
         * 如果有解析，就判断IP是否已经变化
         */
        if (count($record) == 1){
            $obj = $record[0];
            if ($obj->Value != $ip){
                /**
                 * IP发生变化，就更改解析记录
                 */
                $request = new UpdateDomainRecordRequest();
                $request->setRecordId($obj->RecordId);
                $request->setType('A');
                $request->setRR('*');
                $request->setValue($ip);
                $client->getAcsResponse($request);
                writeLog(['action'=>'add_record','old_ip'=>$obj->Value,'new_ip'=>$ip]);
            }
        }
    }
//    $url = "http://alidns.aliyuncs.com/?Action=DescribeDomains&PageNumber=1&PageSize=99&公共请求参数";
//    $request = new
} catch (\GuzzleHttp\Exception\GuzzleException $e) {

}
function writeLog($array){
    $file = __DIR__.'/ip.json';
    if (file_exists($file))
        $old = json_decode(file_get_contents($file),true);
    else
        $old = [];
    $data = array_push($old,$array);
    file_put_contents($file,json_encode($data));
}